import React, { useState, useEffect } from 'react';
import { Tree, message, Spin, Empty } from 'antd';
import request from '../../utils/request';
import { 
  InspectionArea
} from '../../api/gis';
import './DataAreaManagement.css';

interface PatrolDataTreeProps {
  planetId: number;
  onNodeClick: (inspectionAreaId: number, dataSetName?: string) => void;
}

const PatrolDataTree: React.FC<PatrolDataTreeProps> = ({ planetId, onNodeClick }) => {
  const [treeData, setTreeData] = useState<InspectionArea[]>([]);
  const [loading, setLoading] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);

  // 获取树数据
  const fetchTreeData = async () => {
    if (!planetId) return;
    
    setLoading(true);
    try {
      const response = await request.get('/GIS/GISInspectDataSearchTree', {
        params: { planet_id: planetId }
      });

      if (response.data?.code === 200) {
        const data = response.data.data;
        setTreeData(data);
        
        // 默认全展开所有节点
        const allKeys: React.Key[] = [];
        data.forEach((item: InspectionArea) => {
          // 添加第一级节点（巡视区）
          allKeys.push(`area_${item.inspection_area_id}`);
          // 添加第二级节点（数据集）
          item.data_set_list.forEach((_, index) => {
            allKeys.push(`dataset_area_${item.inspection_area_id}_index_${index}`);
          });
        });
        setExpandedKeys(allKeys);
      }
    } catch (error) {
      console.error('获取巡视数据树失败:', error);
      message.error('获取巡视数据树失败');
    } finally {
      setLoading(false);
    }
  };



  // 处理树节点点击
  const handleTreeSelect = (selectedKeys: React.Key[], info: any) => {
    console.log('PatrolDataTree 节点点击:', { selectedKeys, nodeKey: info.node.key });
    
    // 如果点击的是第一级节点（巡视区）
    if (info.node.key && info.node.key.startsWith('area_')) {
      const inspectionAreaId = parseInt(info.node.key.replace('area_', ''));
      console.log('点击巡视区节点:', { inspectionAreaId, nodeKey: info.node.key });
      
      // 查找对应的巡视区数据
      const inspectionArea = treeData.find(area => area.inspection_area_id === inspectionAreaId);
      if (inspectionArea) {
        setSelectedKeys(selectedKeys);
        // 点击巡视区时，通知父组件查询该巡视区下的所有探测点
        console.log('调用 onNodeClick:', inspectionAreaId);
        onNodeClick(inspectionAreaId);
      } else {
        console.log('未找到对应的巡视区数据:', inspectionAreaId);
      }
      return;
    }
    
    // 如果点击的是第二级节点（数据集），设置选中状态并获取文件数据
    if (info.node.key && info.node.key.startsWith('dataset_area_')) {
      setSelectedKeys(selectedKeys);
      
      // 解析key格式：dataset_area_{areaId}_index_{index}
      const match = info.node.key.match(/dataset_area_(\d+)_index_(\d+)/);
      if (match) {
        const areaId = parseInt(match[1]);
        const datasetIndex = parseInt(match[2]);
        
        // 查找对应的巡视区和数据集
        const area = treeData.find(a => a.inspection_area_id === areaId);
        if (area && area.data_set_list[datasetIndex]) {
          const dataSetName = area.data_set_list[datasetIndex];
          
          // 通知父组件按巡视区和数据集名称查询
          onNodeClick(areaId, dataSetName);
        } else {
          message.error('无法找到对应的巡视区或数据集信息');
        }
      } else {
        message.error('无效的数据集节点');
      }
    }
  };

  // 处理树节点展开（保留原有功能，但主要用于图标点击）
  const handleTreeExpand = (expandedKeys: React.Key[]) => {
    setExpandedKeys(expandedKeys);
  };

  // 构建树结构数据
  const buildTreeData = () => {
    return treeData.map((area) => ({
      title: (
        <span>
          {area.inspection_area_name}
        </span>
      ),
      key: `area_${area.inspection_area_id}`,
      className: 'level-1-node',
      children: area.data_set_list
        .map((datasetName, index) => ({
          title: (
            <span>
              {datasetName}
            </span>
          ),
          // 使用巡视区ID和索引确保key的唯一性，避免重复
          key: `dataset_area_${area.inspection_area_id}_index_${index}`,
          isLeaf: true,
          className: 'level-2-node',
        })),
    }));
  };

  // 监听planetId变化
  useEffect(() => {
    if (planetId) {
      fetchTreeData();
    }
  }, [planetId]);

  return (
    <div style={{ marginBottom: 16 }}>
      <div className="data-area-tree-container" style={{ display: 'block', maxHeight: '400px', overflow: 'auto', padding: 12 }}>
        <Spin spinning={loading}>
          {treeData.length > 0 ? (
            <Tree
              blockNode
              expandedKeys={expandedKeys}
              selectedKeys={selectedKeys}
              onSelect={handleTreeSelect}
              onExpand={handleTreeExpand}
              treeData={buildTreeData()}
            />
          ) : (
            <Empty description="暂无巡视数据" style={{ padding: '20px 0' }} />
          )}
        </Spin>
      </div>
    </div>
  );
};

export default PatrolDataTree;
